package com.joint.web.action.app;

import com.fz.us.base.bean.BaseEnum;
import com.fz.us.base.bean.Pager;
import com.fz.us.base.bean.Result;
import com.fz.us.base.util.LogUtil;
import com.fz.us.base.util.mapper.BeanMapper;
import com.fz.us.dict.entity.Dict;
import com.fz.us.dict.service.DictService;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.joint.base.bean.EnumManage;
import com.joint.base.entity.FileManage;
import com.joint.base.entity.Users;
import com.joint.base.entity.system.Locations;
import com.joint.base.util.DataUtil;
import com.joint.core.entity.ProBack;
import com.joint.core.entity.ProInfo;
import com.joint.core.service.EcPushLogService;
import com.joint.core.service.ProBackService;
import com.joint.core.service.ProInfoService;
import com.joint.web.action.BaseAction;
import com.opensymphony.xwork2.ModelDriven;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.util.*;

/**
 * 后台Action类 - 项目反馈管理
 */
@ParentPackage("app")
public class ProbackAction extends BaseAction implements ModelDriven<ProBack> {

    private static final long serialVersionUID = -4787241461181578464L;

    private ProBack proBack;
    private ProBack proBackTemp;
	private List<ProBack> probackList;

    private ProInfo proInfo;
    private String proinfoId;
    private String categoryId;

    private String regular;
    private String noticeIds;

    private Dict category;
    private String addressBack;
    private String latitude;
    private String longitude;
    private String backdate;

    private String photoIds;
    private File photo;
    private String photoFileName;
    private String photoContentType;

    @Resource
    private ProInfoService proInfoService;
    @Resource
    private ProBackService proBackService;
    @Resource
    private DictService dictService;
    @Resource
    protected EcPushLogService ecPushLogService;

    /**
     * 上传照片
     * @return
     * @throws Exception
     */
    public String uploadPhoto() throws Exception {
//        LogUtil.info("upload keyId:"+keyId);
        users = getRequestUsers();
        company = users.getCompany();
        if(company == null)
            return ajaxHtmlAppResult(0, "未找到用户所属企业！",null);

        if (StringUtils.isNotEmpty(keyId)) {

            proBack = proBackService.get(keyId);
            if (proBack != null) {
                if(photo != null){
                    FileManage fileManage = gridFSSave(keyId, ProBack.class, new FileInputStream(photo), photoContentType, photoFileName, company, users);
                    Set<FileManage> picsUrl = Sets.newHashSet();
                    if(proBack.getPicsUrl()!=null){
                        picsUrl = proBack.getPicsUrl();
                    }
                    picsUrl.add(fileManage);
                    proBack.setPicsUrl(picsUrl);
                    proBackService.updateAndEnable(proBack);

                    return ajaxHtmlAppResult(1, "上传成功！", null);
                }
            }
        }
        return ajaxHtmlAppResult(0, "上传失败！", null);
    }

    /**
     * 项目反馈信息创建&修改
     *
     * @return String
     * @throws Exception
     */
    public String create() throws Exception {
        users = getRequestUsers();
        company = users.getCompany();
        if(company == null)
            return ajaxHtmlAppResult(0, "未找到用户所属企业！",null);

        ProBack preBack = null;
        Locations locations = new Locations();
        //具体操作
        if(StringUtils.isEmpty(keyId)){
            //尚未保存过，现在保存
            proInfo = proInfoService.get(proinfoId);
            if(proInfo == null){
                return ajaxHtmlAppResult(0, "未找到所属项目！",null);
            }
            proBack.setProInfo(proInfo);
            proBack.setName(proInfo.getName());
            proBack.setCreater(users);
            proBack.setCompany(company);
            proBack.setAddress(addressBack);

            locations.setLatitude(new BigDecimal(latitude));
            locations.setLongitude(new BigDecimal(longitude));
            locations.setCoordType(EnumManage.CoordTypeEnum.bd09ll);
            locations.setAddress(addressBack);

        }else{
            //已经保存过，现在修改
            proBackTemp = proBackService.get(keyId);
            preBack = BeanMapper.map(proBackTemp, ProBack.class);
        }

        //对象属性获取
        if(StringUtils.isNotEmpty(categoryId)){
            category = dictService.get(categoryId);
            proBack.setCategory(category);
            if(proBackTemp!=null){
                proBackTemp.setCategory(category);
            }
        }

        proBack.setBackDate(DataUtil.StringToDate(backdate, "yyyy-MM-dd"));
        if(proBackTemp!=null){
            proBackTemp.setBackDate(DataUtil.StringToDate(backdate, "yyyy-MM-dd"));
        }

        if(StringUtils.isNotEmpty(noticeIds)){
            String[] noticeId = noticeIds.split(";");
            if (noticeId!=null && noticeId.length>0) {
                Set<Users> group = new HashSet<Users>();
                for(String userId : noticeId){
                    if(StringUtils.isEmpty(userId)) continue;
                    //LogUtil.info("userId:"+userId);
                    Users user = usersService.get(userId);
                    group.add(user);
                }
                proBack.setNotice(group);
                if(proBackTemp!=null){
                    proBackTemp.setNotice(group);
                }
            }
        }
        Result result;
        if(proBackTemp!=null){
            proBackTemp.setContent(proBack.getContent());
            proBackTemp.setMark(proBack.getMark());
            proBackTemp.setRegular(proBack.getRegular());
            proBackService.updateAndResume(proBackTemp,preBack,locations);
            result = new Result(1, proBackTemp.getId());
            //通知相关用户查看该反馈
            ecPushLogService.sendProbackNotification(proBackTemp);
        }else{
            proBackService.updateAndResume(proBack, preBack, locations);
            result = new Result(1, proBack.getId());
            //通知相关用户查看该反馈
            ecPushLogService.sendProbackNotification(proBack);
        }

        return ajaxHtmlAppResult(result);
    }

    /**
     * 初始化反馈详情
     *
     * @return String
     * @throws Exception
     */
    public String initDetail() throws Exception {
        users = getRequestUsers();
        company = users.getCompany();
        if(company == null)
            return ajaxHtmlAppResult(0, "未找到用户所属企业！",null);

        if (StringUtils.isNotEmpty(proinfoId)) {

            proInfo = proInfoService.get(proinfoId);
            if(proInfo == null)
                return ajaxHtmlAppResult(0, "未找到所属项目！",null);

            proBack = new ProBack();
            proBack.setProInfo(proInfo);

            Map<String, Object> data = proBackService.getDetailMap(proBack);
            LogUtil.info("data:" + data);
            return ajaxHtmlAppResult(1, "", JSONObject.fromObject(data));
        }

        return ajaxHtmlAppResult(0, "初始化信息失败！", null);
    }

	/**
	 * 项目反馈列表
	 * @return String
	 * @throws Exception
	 */
	public String getList() throws Exception {

        pager = new Pager();
        pager.setPageNumber(pageIndex);// 页码
        pager.setPageSize(pageSize);// 页Size
        if(StringUtils.isNotEmpty(pageProperty)&&StringUtils.isNotEmpty(pageKeyword)){
            pager.setProperty(pageProperty);
            pager.setKeyword(pageKeyword);
        }
        pager.setOrderBy("createDate");
        pager.setOrderType(BaseEnum.OrderType.desc);

        Map<String, Object> map;
        map = Maps.newHashMap();
//        map.put("state", new BaseEnum.StateEnum[]{BaseEnum.StateEnum.Enable});
        map.put("name", pageKeyword);
        pager = proBackService.findByPagerAndCompany(pager,null,usersService.getCompanyByUser(),map);

        probackList = (List<ProBack>) pager.getList();
        if(probackList == null){
            probackList = new ArrayList<ProBack>();
        }

        List<JSONObject> dataRows = new ArrayList<JSONObject>();
        Map<String, Object> data = new HashMap<String, Object>();

        for (ProBack temp : probackList) {
            Map<String, Object> tempMap = proBackService.getListItemMap(temp);
            dataRows.add(JSONObject.fromObject(tempMap));
        }

        data.put("pageNum", pageIndex);//页数
        data.put("pageSize", probackList.size());//记录数
        data.put("pageCount", pager.getPageCount());//总页数
        data.put("totalCount", pager.getTotalCount());//总记录数
        data.put("dataRows", JSONArray.fromObject(dataRows));//数据
        return ajaxHtmlAppResult(1, "", JSONObject.fromObject(data));
	}

    /**
     * 某一项目下的反馈列表
     * @return String
     * @throws Exception
     */
    public String getListAboutProinfo() throws Exception {

        if(StringUtils.isNotEmpty(proinfoId)){
            proInfo = proInfoService.get(proinfoId);
        }else{
            return ajaxHtmlAppResult(0, "无法找到该项目信息文档，可能已被删除！", null);
        }

        pager = new Pager();
        pager.setPageNumber(pageIndex);// 页码
        pager.setPageSize(pageSize);// 页Size

        pager.setOrderBy("createDate");
        pager.setOrderType(BaseEnum.OrderType.desc);

        Map<String, Object> map;
        map = Maps.newHashMap();
        map.put("state", new BaseEnum.StateEnum[]{BaseEnum.StateEnum.Enable});
        map.put("proInfo",proInfo);
//        map.put("name", pageKeyword);
        pager = proBackService.findByPager(pager, map);

        probackList = (List<ProBack>) pager.getList();
        if(probackList == null){
            probackList = new ArrayList<ProBack>();
        }

        List<JSONObject> dataRows = new ArrayList<JSONObject>();
        Map<String, Object> data = new HashMap<String, Object>();

        if (probackList.size() > 0) {
            for (ProBack temp : probackList) {
                Map<String, Object> tempMap = proBackService.getListItemMap(temp);
                dataRows.add(JSONObject.fromObject(tempMap));
            }
        }

        data.put("pageNum", pageIndex);//页数
        data.put("pageSize", probackList.size());//记录数
        data.put("pageCount", pager.getPageCount());//总页数
        data.put("totalCount", pager.getTotalCount());//总记录数
        data.put("dataRows", JSONArray.fromObject(dataRows));//数据
        return ajaxHtmlAppResult(1, "", JSONObject.fromObject(data));
    }

    /**
     * 和用户相关的反馈列表(在通知对象里面)
     * @return String
     * @throws Exception
     */
    public String getListAboutMe() throws Exception {
        List<JSONObject> dataRows = new ArrayList<JSONObject>();
        Map<String, Object> data = new HashMap<String, Object>();

        pager = new Pager();
        pager.setPageNumber(pageIndex);// 页码
        pager.setPageSize(pageSize);// 页Size
        if(StringUtils.isNotEmpty(pageProperty)&&StringUtils.isNotEmpty(pageKeyword)){
            pager.setProperty(pageProperty);
            pager.setKeyword(pageKeyword);
        }
        pager.setOrderBy("createDate");
        pager.setOrderType(BaseEnum.OrderType.desc);

        Map<String, Object> map;
        map = Maps.newHashMap();
        map.put("name", pageKeyword);
        map.put("company", usersService.getCompanyByUser());
        map.put("state", new BaseEnum.StateEnum[]{BaseEnum.StateEnum.Enable});

        Users user = getRequestUsers();
        DetachedCriteria detachedCriteria = DetachedCriteria.forClass(ProBack.class);
        detachedCriteria.add(Restrictions.sqlRestriction("this_.id in(select id from ec_proback_notice as epn where epn.userId='" + user.getId() + "')"));
//        pager = proBackService.findByPagerAndCompany(pager,null,usersService.getCompanyByUser(),map);
        pager = proBackService.findByPager(pager,detachedCriteria,null,null,null,null,map);

        probackList = (List<ProBack>) pager.getList();
        if(probackList == null){
            probackList = new ArrayList<ProBack>();
        }else{
            for (ProBack temp : probackList) {
                Map<String, Object> tempMap = proBackService.getListItemMap(temp);
                dataRows.add(JSONObject.fromObject(tempMap));
            }
        }

        data.put("pageNum", pageIndex);//页数
        data.put("pageSize", probackList.size());//记录数
        data.put("pageCount", pager.getPageCount());//总页数
        data.put("totalCount", pager.getTotalCount());//总记录数
        data.put("dataRows", JSONArray.fromObject(dataRows));//数据
        return ajaxHtmlAppResult(1, "", JSONObject.fromObject(data));
    }

	/**
	 * 联系人信息详情
     *
	 * @return String
	 * @throws Exception
	 */
	public String getDetail() throws Exception {

        if (StringUtils.isNotEmpty(keyId)) {
            proBack = proBackService.get(keyId);
            if (proBack != null) {
                Map<String, Object> data = proBackService.getDetailMap(proBack);
                return ajaxHtmlAppResult(1, "", JSONObject.fromObject(data));
            }
        }
        return ajaxHtmlAppResult(0, "无法找到该文档，可能已被删除！", null);
	}

	@Override
	public ProBack getModel() {
		if(proBack == null){
            proBack = new ProBack();
		}
		return proBack;
	}

    public ProBack getProBack() {
        return proBack;
    }

    public void setProBack(ProBack proBack) {
        this.proBack = proBack;
    }

    public String getProinfoId() {
        return proinfoId;
    }

    public void setProinfoId(String proinfoId) {
        this.proinfoId = proinfoId;
    }

    public String getCategoryId() {
        return categoryId;
    }

    public void setCategoryId(String categoryId) {
        this.categoryId = categoryId;
    }

    public String getRegular() {
        return regular;
    }

    public void setRegular(String regular) {
        this.regular = regular;
    }

    public String getNoticeIds() {
        return noticeIds;
    }

    public void setNoticeIds(String noticeIds) {
        this.noticeIds = noticeIds;
    }

    public String getPhotoIds() {
        return photoIds;
    }

    public void setPhotoIds(String photoIds) {
        this.photoIds = photoIds;
    }

    public String getLatitude() {
        return latitude;
    }

    public void setLatitude(String latitude) {
        this.latitude = latitude;
    }

    public String getLongitude() {
        return longitude;
    }

    public void setLongitude(String longitude) {
        this.longitude = longitude;
    }

    public File getPhoto() {
        return photo;
    }

    public void setPhoto(File photo) {
        this.photo = photo;
    }

    public String getPhotoFileName() {
        return photoFileName;
    }

    public void setPhotoFileName(String photoFileName) {
        this.photoFileName = photoFileName;
    }

    public String getPhotoContentType() {
        return photoContentType;
    }

    public void setPhotoContentType(String photoContentType) {
        this.photoContentType = photoContentType;
    }

    public String getBackdate() {
        return backdate;
    }

    public void setBackdate(String backdate) {
        this.backdate = backdate;
    }

    public String getAddressBack() {
        return addressBack;
    }

    public void setAddressBack(String addressBack) {
        this.addressBack = addressBack;
    }
}
